import requests
import hashlib
import time
import random


def get_signature(text, salt):
    """生成搜狗翻译的签名"""
    sign_str = f"auto{text}{salt}]AueJ7GyfxN5iC3"
    return hashlib.md5(sign_str.encode('utf-8')).hexdigest()


def get_translation(text):
    """获取搜狗翻译结果"""
    # 生成时间戳和随机salt
    timestamp = int(time.time() * 1000)
    salt = str(timestamp) + str(random.randint(0, 9))
    sign = get_signature(text, salt)

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Origin': 'https://fanyi.sogou.com',
        'Referer': 'https://fanyi.sogou.com/',
    }

    params = {
        'from': 'auto',
        'to': 'zh-CHS',
        'text': text,
        'client': 'pc',
        'fr': 'browser_pc',
        'pid': 'sogou-dict-vr',
        'dict': 'true',
        'word_group': 'true',
        'second_query': 'true',
        'uuid': str(timestamp),
        'needQc': '1',
        's': sign,
        'salt': salt,
    }

    try:
        response = requests.post(
            'https://fanyi.sogou.com/api/transpc/text/result',
            headers=headers,
            data=params
        )
        result = response.json()

        if result.get('data', {}).get('translate', {}).get('dit'):
            return result['data']['translate']['dit']
        return "未找到翻译结果"

    except Exception as e:
        return f"翻译出错: {str(e)}"


def main():
    print("搜狗翻译工具 (输入'q'退出)")
    while True:
        text = input("\n请输入要翻译的内容: ").strip()
        if text.lower() == 'q':
            break
        if not text:
            continue

        print("翻译结果:", get_translation(text))


if __name__ == '__main__':
    main()